package cn.lili.controller.walletAll;

import cn.lili.common.enums.ResultUtil;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawApply;
import cn.lili.modules.wallet.entity.dos.WalletDetail;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.enums.WithdrawStatusEnum;
import cn.lili.modules.wallet.entity.vo.MemberWithdrawApplyVO;
import cn.lili.modules.wallet.entity.vo.WalletDetailVO;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.MemberWithdrawApplyService;
import cn.lili.modules.wallet.service.WalletDetailService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/manager/WalletAll/processData")
public class ProcessDataController {

    @Autowired
    MemberWithdrawApplyService memberWithdrawApplyService;

    @Autowired
    WalletDetailService walletDetailService;

    @Autowired
    MemberWalletService memberWalletService;

    @Autowired
    TransferService transferService;

    @Autowired
    MemberService memberService;

    @ApiOperation(value = "提现记录")
    @RequestMapping("/memberWithdrawApply")
    public Map<String, List> memberWithdrawApply() {
        Map<String, List> map = new HashMap<>();
        // 提现记录
        QueryWrapper<MemberWithdrawApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("apply_status", "APPLY","FINISH", "VIA_AUDITING");
        List<MemberWithdrawApplyVO> listAll = memberWithdrawApplyService.getListAll(queryWrapper);
        //钱包明细
        List<WalletDetail> list = walletDetailService.getUnRefund();
        // 找出相同的数据
        List<MemberWithdrawApplyVO> list1 = new ArrayList<>();
        for (MemberWithdrawApplyVO apply : listAll) {
            boolean bool = list.stream().anyMatch(a -> a.getSn().equals(apply.getSn()) && a.getMoney().compareTo(apply.getApplyPrice()) == 0);
            if(bool){
                list1.add(apply);
            }
        }
        List<WalletDetail> list2 = new ArrayList<>();
        for (WalletDetail wd : list) {
            boolean bool = listAll.stream().anyMatch(a -> a.getSn().equals(wd.getSn()) && wd.getMoney().compareTo(a.getApplyPrice()) == 0);
            if(bool){
                list2.add(wd);
            }
        }
        // 移除相同数据
        listAll.removeAll(list1);
        list.removeAll(list2);
        map.put("apply",listAll);
        map.put("WalletDetail",list);
        // 新增钱包明细
        if(!CollectionUtils.isEmpty(listAll)){
            MemberWallet admin = memberWalletService.getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台"); // 平台余额
            for (MemberWithdrawApplyVO apply : listAll) {
                WalletDetail detail = new WalletDetail();
                WalletDetail one = walletDetailService.getOne(new QueryWrapper<WalletDetail>().eq("sn", apply.getSn()).eq("transaction_type", "WALLET_WITHDRAWAL"));
                if(one == null) {
                    detail.setSn(apply.getSn());
                    detail.setTransactionType(DepositServiceTypeEnum.WALLET_WITHDRAWAL.name());
                    detail.setPayer(apply.getMemberId());
                    detail.setPayerName(apply.getMemberName());
                    detail.setPayerOwner(apply.getOwner());

                    detail.setPayee(admin.getMemberId());
                    detail.setPayeeName(admin.getMemberName());
                    detail.setPayeeOwner(admin.getOwner());

                    detail.setMoney(apply.getApplyPrice());
                    detail.setRemark("补数据");
                    walletDetailService.save(detail);
                }else{
                    detail.setMoney(apply.getApplyPrice());
                    walletDetailService.update(detail,new QueryWrapper<WalletDetail>().eq("sn", apply.getSn()));
                }
            }
        }
        // 新增提现明细
        if(!CollectionUtils.isEmpty(list)){
            for (WalletDetail wd : list) {
                MemberWithdrawApply memberWithdrawApply = new MemberWithdrawApply();
                MemberWithdrawApply one = memberWithdrawApplyService.getOne(new QueryWrapper<MemberWithdrawApply>().eq("sn", wd.getSn()));
                if(one == null) {
                    memberWithdrawApply.setMemberId(wd.getPayer());
                    Member member = memberService.getById(wd.getPayer());
                    if(member!= null) {
                        memberWithdrawApply.setMemberName(member.getNickName());
                    }
                    memberWithdrawApply.setApplyPrice(wd.getMoney());
                    memberWithdrawApply.setOwner(wd.getPayerOwner());
                    memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.FINISH.name());
                    memberWithdrawApply.setSn(wd.getSn());
                    memberWithdrawApply.setInspectTime(new Date());
                    memberWithdrawApply.setFinishTime(new Date());
                    memberWithdrawApply.setFee(0D);
                    memberWithdrawApplyService.save(memberWithdrawApply);
                }
            }
        }
        return map;
    }

    @ApiOperation(value = "转账记录")
    @RequestMapping("/transfer")
    public Map<String, List> transfer() {
        Map<String, List> map = new HashMap<>();
        // 转账记录
        QueryWrapper<Transfer> queryWrapper = new QueryWrapper<>();
        List<Transfer> listAll = transferService.list(queryWrapper);
        //钱包明细
        List<WalletDetailVO> list = walletDetailService.getTransfer();
        // 找出相同的数据
        List<Transfer> list1 = new ArrayList<>();
        for (Transfer transfer : listAll) {
            boolean bool = list.stream().anyMatch(a -> a.getSn().equals(transfer.getSn()) && a.getMoney().compareTo(transfer.getTransferMoney()) == 0);
            if(bool){
                list1.add(transfer);
            }
        }
        List<WalletDetailVO> list2 = new ArrayList<>();
        for (WalletDetailVO wd : list) {
            boolean bool = listAll.stream().anyMatch(a -> a.getSn().equals(wd.getSn()) && wd.getMoney().compareTo(a.getTransferMoney()) == 0);
            if(bool){
                list2.add(wd);
            }
        }
        // 移除相同数据
        listAll.removeAll(list1);
        list.removeAll(list2);
        map.put("transfer",listAll);
        map.put("WalletDetail",list);
        // 新增钱包明细
        if(!CollectionUtils.isEmpty(listAll)){
            MemberWallet admin = memberWalletService.getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台"); // 平台余额
            for (Transfer transfer : listAll) {
                WalletDetail detail = new WalletDetail();
                WalletDetail one = walletDetailService.getOne(new QueryWrapper<WalletDetail>().eq("sn", transfer.getSn()).ne("transaction_type", "WALLET_COMMISSION_FW"));
                List<WalletDetail> commission = walletDetailService.list(
                    new QueryWrapper<WalletDetail>().eq("sn", transfer.getSn())
                        .eq("transaction_type", "WALLET_COMMISSION_FW"));
                if(one == null) {
                    String userName = null;
                    if("admin".equals(transfer.getPayer())){
                        userName = "平台";
                    }else{
                        Member member = memberService.getById(transfer.getPayer());
                        userName = member != null ? member.getUsername() : null;
                    }

                    detail.setSn(transfer.getSn());
                    if("PORT_FEE".equals(transfer.getType())) {// 端口费
                        detail.setTransactionType(DepositServiceTypeEnum.WALLET_COMMISSION_FW_REFUND.name());
                    }else{// 转账
                        detail.setTransactionType(DepositServiceTypeEnum.WALLET_PAY.name());
                    }
                    detail.setPayer(transfer.getPayer());
                    detail.setPayerName(userName);
                    detail.setPayerOwner(transfer.getPaymentWallet());

                    detail.setPayee(transfer.getPayee());
                    detail.setPayeeName(transfer.getPayeeName());
                    detail.setPayeeOwner("RECHARGE");

                    detail.setMoney(transfer.getTransferMoney());
                    detail.setRemark("补数据");
                    walletDetailService.save(detail);
                    if(new Double(0).compareTo(new Double(transfer.getCommission())) != 0) {
                        //补手续费
                        WalletDetail detail1 = new WalletDetail();
                        detail1.setSn(transfer.getSn());
                        detail1.setTransactionType(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name());
                        detail1.setPayer(transfer.getPayer());
                        detail1.setPayerName(userName);
                        detail1.setPayerOwner(transfer.getPaymentWallet());

                        detail1.setPayee(admin.getMemberId());
                        detail1.setPayeeName(admin.getMemberName());
                        detail1.setPayeeOwner(admin.getOwner());

                        detail1.setMoney(transfer.getCommission());
                        detail1.setRemark("补手续费");
                        walletDetailService.save(detail1);
                    }
                }else{
                    detail.setMoney(transfer.getTransferMoney());
                    walletDetailService.update(detail,new QueryWrapper<WalletDetail>().eq("sn", transfer.getSn()).eq("transaction_type", "WALLET_PAY"));
                    if(!CollectionUtils.isEmpty(commission)){
                        // 补手续费
                        if(commission.size() == 1){
                            // 只有平台
                            WalletDetail detailpt = new WalletDetail();
                            detailpt.setId(commission.get(0).getId());
                            detailpt.setMoney(transfer.getCommission());
                            walletDetailService.updateById(detailpt);
                        }else{
                            // 平台和城市
                            WalletDetail detailpt = new WalletDetail();
                            WalletDetail detailcs = new WalletDetail();
                            if("admin".equals(commission.get(0).getPayee())){
                                detailpt.setId(commission.get(0).getId());
                                detailpt.setMoney(CurrencyUtil.div(transfer.getCommission(),2,2));
                                walletDetailService.updateById(detailpt);

                                detailcs.setId(commission.get(0).getId());
                                detailcs.setMoney(CurrencyUtil.div(transfer.getCommission(),2,2));
                                walletDetailService.updateById(detailcs);
                            }else{
                                detailpt.setId(commission.get(0).getId());
                                detailpt.setMoney(CurrencyUtil.div(transfer.getCommission(),2,2));
                                walletDetailService.updateById(detailpt);

                                detailcs.setId(commission.get(0).getId());
                                detailcs.setMoney(CurrencyUtil.div(transfer.getCommission(),2,2));
                                walletDetailService.updateById(detailcs);

                            }
                        }
                    }
                }
            }
        }
        // 新增转账明细
        if(!CollectionUtils.isEmpty(list)){
            for (WalletDetailVO wd : list) {
                Transfer transfer = new Transfer();
                Transfer one = transferService.getOne(new QueryWrapper<Transfer>().eq("sn", wd.getSn()));
                if(one == null) {
                    transfer.setPayee(wd.getPayee());
                    transfer.setPayeeCard(wd.getCardName());
                    Member payee = memberService.getById(wd.getPayee());
                    transfer.setPayeeName(payee != null ? payee.getNickName() : null);
                    transfer.setPayeePhone(payee != null ? payee.getMobile() : null);
                    transfer.setPayeeImg(payee != null ? payee.getFace() : null);
                    transfer.setTransferMoney(wd.getMoney());
                    transfer.setCommission(wd.getSumMoney());
                    transfer.setPaymentWallet(wd.getPayerOwner());
                    transfer.setPayer(wd.getPayer());
                    Member byId = memberService.getById(wd.getPayer());
                    transfer.setPayerPhone(byId != null ? byId.getMobile() : null);
                    transfer.setSn(wd.getSn());
                    transfer.setPaymentTime(new Date());
                    transfer.setState("success");
                    if("WALLET_COMMISSION_FW_REFUND".equals(wd.getTransactionType()))
                        transfer.setType("PORT_FEE");// 端口费
                    else
                        transfer.setType("TRANSFER");// 转账
                    transferService.save(transfer);
                }
            }
        }
        return map;
    }
}
